package com.wephone.Student.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import org.apache.http.util.EncodingUtils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wephone.Student.R;
import com.wephone.Student.bean.data.CountryData;
import com.wephone.Student.ui.NewRegisterActivity2;

public class Util {
	private static final double EARTH_RADIUS = 6378137.0;
	
	public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		bmp.compress(CompressFormat.PNG, 100, output);
		if (needRecycle) {
			bmp.recycle();
		}
		
		byte[] result = output.toByteArray();
		try {
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	public static boolean checkEmail(String email){
		if(!TextUtils.isEmpty(email) && email.matches("[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?")){
			return true;
		}
		return false;
	}
	
	public static String formatDate(long time){
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df.format(new Date(time));
	}
	
	public static String getConstellationStr(Context context,int month,int day){
		String[] constellationArray = context.getResources().getStringArray(R.array.register_constellations_array);
		if(month==1){
			if(day<=19){
				return constellationArray[9];
			}else{
				return constellationArray[10];
			}
		}else if(month==2){
			if(day<=18){
				return constellationArray[10];
			}else{
				return constellationArray[11];
			}
		}else if(month==3){
			if(day<=20){
				return constellationArray[11];
			}else{
				return constellationArray[0];
			}
		}else if(month==4){
			if(day<=19){
				return constellationArray[0];
			}else{
				return constellationArray[1];
			}
		}else if(month==5){
			if(day<=20){
				return constellationArray[1];
			}else{
				return constellationArray[2];
			}
		}else if(month==6){
			if(day<=21){
				return constellationArray[2];
			}else{
				return constellationArray[3];
			}
		}else if(month==7){
			if(day<=22){
				return constellationArray[3];
			}else{
				return constellationArray[4];
			}
		}else if(month==8){
			if(day<=22){
				return constellationArray[4];
			}else{
				return constellationArray[5];
			}
		}else if(month==9){
			if(day<=22){
				return constellationArray[5];
			}else{
				return constellationArray[6];
			}
		}else if(month==10){
			if(day<=23){
				return constellationArray[6];
			}else{
				return constellationArray[7];
			}
		}else if(month==11){
			if(day<=22){
				return constellationArray[7];
			}else{
				return constellationArray[8];
			}
		}else{
			if(day<=21){
				return constellationArray[8];
			}else{
				return constellationArray[9];
			}
		}
	}
	
	public static void saveMyBitmap(Bitmap bitmap,String fileName,Context context){
		String pathString;
		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        {
			
			pathString = Constants.IMAGE_PHOTO_TMP_PATH;
        }else{
        	
        		pathString = context.getCacheDir().getAbsolutePath()+"/";
        }
		File dirFile = new File(pathString);
		if(!dirFile.exists()){
			dirFile.mkdirs();
		}
	    File f = new File(pathString+fileName);
	    if(!f.exists()){
	    	try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
	    }
	    FileOutputStream fOut = null;
	    try {
	    	 fOut = new FileOutputStream(f);
	    	 if (null != fOut) {
	    		 Bitmap bm = bitmap.copy(Bitmap.Config.ARGB_8888, false);
	    		 bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
	    		 fOut.flush();
	    	 }
	    } catch (Exception e) {
            e.printStackTrace();
	    }finally{
	    	if(fOut!=null){
	    		try {
					fOut.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
	    	}
	    }
	}
	
	public static String saveBitmapToGallery(Bitmap bitmap,String fileName){
		File dirFile = new File(Constants.IMAGE_PHOTO_GALLERY_PATH);
		if(!dirFile.exists()){
			dirFile.mkdirs();
		}
	    File f = new File(Constants.IMAGE_PHOTO_GALLERY_PATH+fileName);
	    if(!f.exists()){
	    	try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
	    }
	    FileOutputStream fOut = null;
	    try {
            fOut = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            fOut.flush();
	    } catch (Exception e) {
            e.printStackTrace();
	    }finally{
	    	if(fOut!=null){
	    		try {
					fOut.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
	    	}
	    }
	    return f.getPath();
	}
	
	public static String getFormatTimeStr(String timeStr){
		long time = System.currentTimeMillis()/1000 - Long.parseLong(timeStr);
		if(time<60*60){
			return time/60+"分钟前";
		}else if(time<60*60*60){
			return time/60/60+"小时前";
		}else if(time<24*60*60*60){
			return time/24/60/60+"天前";
		}else if(time<30*24*60*60*60){
			return time/30/24/60/60+"个月前";
		}
		return "很久以前";
	}
	
	public static double gps2km(String lat_a, String lng_a, String lat_b, String lng_b) {
//	   System.out.println("-----lat_a-----"+lat_a);
//	   System.out.println("-----lng_a-----"+lng_a);
//	   System.out.println("-----lat_b-----"+lat_b);
//	   System.out.println("-----lng_b-----"+lng_b);
       double radLat1 = (Double.parseDouble(lat_a) * Math.PI / 180.0);
       double radLat2 = (Double.parseDouble(lat_b) * Math.PI / 180.0);
       double a = radLat1 - radLat2;
       double b = (Double.parseDouble(lng_a) - Double.parseDouble(lng_b)) * Math.PI / 180.0;
       double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
       s = s * EARTH_RADIUS;
       s = Math.round(s * 10000) / 10000;
       return s/1000;
    }
	
	public static Bitmap decodeFile(String path) {
        try {
            if (path == null) {
                return null;
            }
//            // decode image size 
//            BitmapFactory.Options o = new BitmapFactory.Options();
//            o.inJustDecodeBounds = true;
//            // Find the correct scale value. It should be the power of 2.
//            final int REQUIRED_SIZE = 200;
//            int width_tmp = o.outWidth, height_tmp = o.outHeight;
//            int scale = 0;
//            while (true) {
//                if (width_tmp / 2 < REQUIRED_SIZE
//                        || height_tmp / 2 < REQUIRED_SIZE)
//                    break;
//                width_tmp /= 2;
//                height_tmp /= 2;
//            scale++;
//            }
//            // decode with inSampleSize
//            BitmapFactory.Options o2 = new BitmapFactory.Options();
//            o2.inSampleSize = scale;
            Bitmap bitmapOrg = BitmapFactory.decodeFile(path);
            Matrix m = new Matrix();
            //获取这个图片的宽和高
            int width = bitmapOrg.getWidth();
            int height = bitmapOrg.getHeight();
            //定义预转换成的图片的宽度和高度
            int newWidth = 300;
            int newHeight = 300;
            //计算缩放率，新尺寸除原始尺寸
            float scaleWidth = ((float) newWidth) / width;
            float scaleHeight = ((float) newHeight) / height;
            // 缩放图片动作
            m.postScale(scaleWidth, scaleHeight);
         
            ExifInterface exif = new ExifInterface(path);
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
            if((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
                m.postRotate(180);
            }else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                m.postRotate(90);
            }else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                m.postRotate(270);
            }
            Bitmap bitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width,height, m, true);
            return bitmap;
        } catch (Exception e) {
            return null;
        }
	}
	
	public static List<CountryData> getCountryList(Context context){
		List<CountryData> countryList = new ArrayList<CountryData>();
		try{
			InputStream in = context.getAssets().open("location_data.txt");
			int len = in.available();
			byte[]  buffer = new byte[len];
			in.read(buffer);
			String result = EncodingUtils.getString(buffer, "utf-8");
			if(!TextUtils.isEmpty(result)){
				Gson gson = new Gson();
				countryList = gson.fromJson(result, new TypeToken<ArrayList<CountryData>>(){}.getType());
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return countryList;
	}
	
	public static String getLocalIpAddress(){
		try{
			for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();){
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()){
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		}catch (SocketException ex){
			ex.printStackTrace();
		}
		return "unknown";
	}  

	public static int getVersionCode(Context context){
		try {
			PackageInfo pi=context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			return pi.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return 0;
		}
	}

	public static int getCountryFlagSrc(String cName){
		if(cName.contains("中国")){
			return R.drawable.user_detail_bg_1;
		}else if(cName.contains("爱尔兰")){
			return R.drawable.user_detail_bg_2;
		}else if(cName.contains("澳大利亚")){
			return R.drawable.user_detail_bg_3;
		}else if(cName.contains("奥地利")){
			return R.drawable.user_detail_bg_4;
		}else if(cName.contains("比利时")){
			return R.drawable.user_detail_bg_5;
		}else if(cName.contains("波兰")){
			return R.drawable.user_detail_bg_6;
		}else if(cName.contains("丹麦")){
			return R.drawable.user_detail_bg_7;
		}else if(cName.contains("德国")){
			return R.drawable.user_detail_bg_8;
		}else if(cName.contains("俄罗斯")){
			return R.drawable.user_detail_bg_9;
		}else if(cName.contains("法国")){
			return R.drawable.user_detail_bg_10;
		}else if(cName.contains("菲律宾")){
			return R.drawable.user_detail_bg_11;
		}else if(cName.contains("芬兰")){
			return R.drawable.user_detail_bg_12;
		}else if(cName.contains("韩国")){
			return R.drawable.user_detail_bg_13;
		}else if(cName.contains("荷兰")){
			return R.drawable.user_detail_bg_14;
		}else if(cName.contains("加拿大")){
			return R.drawable.user_detail_bg_15;
		}else if(cName.contains("马来西亚")){
			return R.drawable.user_detail_bg_16;
		}else if(cName.contains("美国")){
			return R.drawable.user_detail_bg_17;
		}else if(cName.contains("南非")){
			return R.drawable.user_detail_bg_18;
		}else if(cName.contains("挪威")){
			return R.drawable.user_detail_bg_19;
		}else if(cName.contains("日本")){
			return R.drawable.user_detail_bg_20;
		}else if(cName.contains("瑞典")){
			return R.drawable.user_detail_bg_21;
		}else if(cName.contains("瑞士")){
			return R.drawable.user_detail_bg_22;
		}else if(cName.contains("泰国")){
			return R.drawable.user_detail_bg_23;
		}else if(cName.contains("乌克兰")){
			return R.drawable.user_detail_bg_24;
		}else if(cName.contains("西班牙")){
			return R.drawable.user_detail_bg_25;
		}else if(cName.contains("新加坡")){
			return R.drawable.user_detail_bg_26;
		}else if(cName.contains("新西兰")){
			return R.drawable.user_detail_bg_27;
		}else if(cName.contains("意大利")){
			return R.drawable.user_detail_bg_28;
		}else if(cName.contains("印度")){
			return R.drawable.user_detail_bg_29;
		}else if(cName.contains("英国")){
			return R.drawable.user_detail_bg_30;
		}
		return R.drawable.user_detail_bg_usa;
	}
	
	public static Bitmap getBitmap(Context context,String path, int maxSize) {
		BitmapFactory.Options op = new Options();
		op.inJustDecodeBounds = true;
		maxSize *= context.getResources().getDisplayMetrics().density;
		BitmapFactory.decodeFile(path, op);
		float outW = op.outWidth;
		float outH = op.outHeight;
		float scale = Math.max(outW / maxSize, outH / maxSize);
		if (scale > 2) {
			op.inSampleSize = (int) scale;
		} else {
			scale = 1;
		}
		op.inJustDecodeBounds = false;
		Bitmap bm = BitmapFactory.decodeFile(path, op);
		if (bm != null) {
			Bitmap temp = bm;
			bm = Bitmap.createScaledBitmap(bm, (int) (outW / scale),
					(int) (outH / scale), true);
			temp.recycle();
			temp = null;
		}
		return bm;
	}

	/**
	 * This method converts dp unit to equivalent pixels, depending on device density. 
	 * 
	 * @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels
	 * @param context Context to get resources and device specific display metrics
	 * @return A float value to represent px equivalent to dp depending on device density
	 */
	public static float convertDpToPixel(float dp, Context context){
	    Resources resources = context.getResources();
	    DisplayMetrics metrics = resources.getDisplayMetrics();
	    float px = dp * (metrics.densityDpi / 160f);
	    return px;
	}
	
	public static float getScreenWidth(Context context){
		DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();

        float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
        float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
        return dpWidth;
	}
	
	public static float getScreenHeight(Context context){
		DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();

        float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
        float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
	    return dpHeight;
	}
	
	/**
	 * This method converts device specific pixels to density independent pixels.
	 * 
	 * @param px A value in px (pixels) unit. Which we need to convert into db
	 * @param context Context to get resources and device specific display metrics
	 * @return A float value to represent dp equivalent to px value
	 */
	public static float convertPixelsToDp(float px, Context context){
	    Resources resources = context.getResources();
	    DisplayMetrics metrics = resources.getDisplayMetrics();
	    float dp = px / (metrics.densityDpi / 160f);
	    return dp;
	}
	
	public static Bitmap compressImage(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while ( baos.toByteArray().length / 1024>50) {	//循环判断如果压缩后图片是否大于100kb,大于继续压缩		
			baos.reset();//重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;//每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
		return bitmap;
	}
	
	public static Bitmap getimage(String srcPath) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		//开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空
		
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		//现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 400f;//这里设置高度为800f
		float ww = 480f;//这里设置宽度为480f
		//缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;//be=1表示不缩放
		if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;//设置缩放比例
		//重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
	}
	
	public static Bitmap comp(Bitmap image) {
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();		
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		if( baos.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出	
			baos.reset();//重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%，把压缩后的数据存放到baos中
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		//开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		//现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 400f;//这里设置高度为400f
		float ww = 480f;//这里设置宽度为480f
		//缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;//be=1表示不缩放
		if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;//设置缩放比例
		//重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		isBm = new ByteArrayInputStream(baos.toByteArray());
		bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
	}
}
